package threadcoreknowledge.stopthreads;

/**
 * @ClassName RightWayStopThreadInProd
 * @Description 最佳实践：catch了InterruptedException之后的优先选择：在方法签名中抛出异常
 *                          那么在run() 就会强制 try/catch
 * @Author wushaopei
 * @Date 2021/2/25 22:53
 * @Version 1.0
 */
public class RightWayStopThreadInProd implements Runnable{

    @Override
    public void run() {
        while(true && !Thread.currentThread().isInterrupted()){
            System.out.println("go");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                // 保存日志、停止程序
                System.out.println("保存日志");
                e.printStackTrace();
            }
        }
    }

    private void throwInMethod() throws InterruptedException {
//        try {
            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}
